﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CarHelpDesk.Web.Models.Repositories;
using CarHelpDesk.Web.Models;
using CarHelpDesk.Web.Utils;
using System.Diagnostics;

namespace CarHelpDesk.Web.Controllers
{
    public class QuestionVotesController : Controller
    {
        private IQuestionsRepository repo { get; set; }

        public QuestionVotesController()
        {
            this.repo = new CarHelpDesk.Web.Models.Repositories.LinqRepositories.QuestionsRepository();
        }

        public QuestionVotesController(IQuestionsRepository questionsRepository)
        {
            this.repo = questionsRepository;
        }

        //
        // POST: /QuestionVotes/Vote
        [HttpPost]
        [Authorize]
        public ActionResult Vote(QuestionVote vote)
        {
            VoteResult result = new VoteResult();

            try
            {
                Question question = this.repo.GetByID(vote.QuestionID);

                //check owner
                if (question.AuthorID == this.GetCurrentUserID())
                {
                    result.Success = false;
                    result.Message = "Не можете да гласувате за въпрос зададен от вас.";
                }
                else
                {
                    //check already voted
                    QuestionVote existingVote = this.repo.GetQuestionVote(question, this.GetCurrentUserID());
                    if (existingVote == null)
                    {
                        //create new vote
                        vote.UserID = this.GetCurrentUserID();
                        vote.CreateDate = DateTime.Now;

                        this.repo.CreateQuestionVote(vote);

                        result.Success = true;
                        result.AlreadyVoted = false;
                        result.VoteValue = vote.VoteValue;
                    }
                    else
                    {
                        //user already voted for question
                        result.Success = true;
                        result.AlreadyVoted = true;
                        result.VoteValue = existingVote.VoteValue;
                        result.Message = "Вече сте гласували за този въпрос";
                    }
                }

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message + ex.StackTrace);
                result.Success = false;
                result.Message = "Грешка";
            }

            return this.Json(result);
        }

        public class VoteResult
        {
            public int VoteValue { get; set; }
            public bool Success { get; set; }
            public bool AlreadyVoted { get; set; }
            public string Message { get; set; }
        }
    }
}
